package com.hm.PushCaseService.task;

import com.hm.PushCaseService.service.valve.IValveService;
import com.hm.PushCaseService.service.ydcg.caseinfo.help.ICaseHelp;
import com.hm.PushCaseService.pojo.CaseBean;
import com.hm.PushCaseService.utils.time.DateTimeUtils;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 定时推送数据任务
 */
@Component
@EnableScheduling
public class PushCaseTask {

    private static final Logger logger = LoggerFactory.getLogger(PushCaseTask.class);

    @Qualifier("ActiveMQTopic_case")
    private final ActiveMQTopic topicCaseInfo;

    @Autowired
    private final JmsTemplate jmsTemplate;

    private final ICaseHelp iCaseHelp;

    private final IValveService iValveService;

    public PushCaseTask(ActiveMQTopic topicCaseInfo, JmsTemplate jmsTemplate, ICaseHelp iCaseHelp, IValveService iValveService) {
        this.topicCaseInfo = topicCaseInfo;
        this.jmsTemplate = jmsTemplate;
        this.iCaseHelp = iCaseHelp;
        this.iValveService = iValveService;
    }

    //容器启动initialDelay执行一次，之后间隔fixedDelay秒执行一次
    @Scheduled(initialDelay = 1000 * 10, fixedDelay = 1000 * 60 * 3)
    private void pushData() {
        //先查询推送开关状态
        String s = iValveService.queryValveState();
        if (s == null || s.equals("1")) {
            logger.warn("======推送开关-关闭======");
            return;
        }
        //获取自行处置案件+专业部门处置案件-》批量入库
        List<CaseBean> allList = new ArrayList<>();
        allList.addAll(iCaseHelp.getSelfDispCaseList());
        allList.addAll(iCaseHelp.getProfessionCaseList());
        //设置入库时间&发消息给推送服务
        for (CaseBean caseBean : allList) {
            caseBean.lastUpdateTime = DateTimeUtils.getCurrentTime();
            //发消息给案件处理接收器
            jmsTemplate.convertAndSend(topicCaseInfo, caseBean);
        }
        //批量入库
        iCaseHelp.insertBatch(allList);
        //更新时间戳
        iCaseHelp.updateTime();
        logger.warn("======推送完成======");
    }

}
